
// import { Settings } from '../interface/settings'
import { Settings } from '../interface/settings'
import NotificationCenter from './notification'
import { fetchSettings } from './settings'



export const SwitchConfigKeys = {
    TonWalletSwitch: 'ton_wallet_switch'
}

export type Dictionary<T> = { [key: string]: T }
export default class SwitchConfig {
    private static config: Dictionary<any> = {}
    static init() {
        // TODO: fetchConfigData
        SwitchConfig.config = {
            [SwitchConfigKeys.TonWalletSwitch]: true
        }

        fetchSettings().then(res => {
            SwitchConfig.updateConfig(res)
        })
    }

    static updateConfig(config: Settings) {
        SwitchConfig.config = {
            ...SwitchConfig.config,
            ...config
        }
        NotificationCenter.post('NotificationSwitchConfigName')
    }

    static objectForKey(name: string, defaultValue?: any): any {
        if (!name) {
            return defaultValue
        }
        const value = SwitchConfig.config?.[name]
        if (value === undefined || value === null) {
            return defaultValue
        }

        return value
    }

    static boolForKey(name: string, defaultValue?: boolean): boolean {
        const value = SwitchConfig.objectForKey(name, defaultValue)
        if (typeof value === 'boolean' || typeof value === 'number') {
            return Boolean(value)
        }

        if (typeof value === 'string') {
            if (value === 'true') {
                return true
            }

            if (value === 'false') {
                return false
            }
            return Boolean(value)
        }

        return defaultValue || false
    }

    static numberForKey(name: string, defaultValue?: number): number {
        const value = SwitchConfig.objectForKey(name, defaultValue)
        if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
            return Number(value)
        }

        return defaultValue || 0
    }

    static arrayForKey<T>(name: string, defaultValue?: Array<T>): Array<T> {
        const value = SwitchConfig.objectForKey(name, defaultValue)
        if (Array.isArray(value)) {
            return value
        }
        return defaultValue || []

    }

    static dicForKey<T>(name: string, defaultValue?: Dictionary<T>): Dictionary<T> {
        const value = SwitchConfig.objectForKey(name, defaultValue)
        if (typeof value === 'object' && !Array.isArray(value) && value !== null) {
            return value
        }
        return defaultValue || {}
    }

}